from playwright.sync_api import sync_playwright
import logging
import time
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename=f'test_baidu_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
)


def main():
    """百度搜索自动化测试脚本"""
    try:
        logging.info("===== 测试开始 =====")

        # 启动浏览器
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False)  # 改为 True 可隐藏浏览器窗口
            page = browser.new_page()

            # 打开百度首页
            logging.info("打开百度首页: https://www.baidu.com")
            page.goto("https://www.baidu.com")
            page.wait_for_load_state("networkidle")  # 等待页面加载完成

            # 定位搜索框并输入内容
            logging.info("定位搜索框")
            search_box = page.locator("#kw")  # 通过 ID 定位
            if not search_box.is_visible():
                raise Exception("搜索框元素未找到或不可见")

            logging.info("输入搜索关键词: Playwright 自动化测试")
            search_box.fill("Playwright 自动化测试")

            # 点击搜索按钮
            logging.info("点击搜索按钮")
            search_button = page.locator("#su")
            search_button.click()

            # 等待搜索结果加载
            page.wait_for_selector(".result.c-container")  # 等待搜索结果出现
            logging.info("搜索结果加载完成")

            # 验证结果
            title = page.title()
            if "Playwright 自动化测试" not in title:
                logging.warning(f"页面标题验证失败: {title}")
            else:
                logging.info(f"页面标题验证成功: {title}")

            # 截图保存
            screenshot_path = f"screenshot_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
            page.screenshot(path=screenshot_path)
            logging.info(f"截图已保存至: {screenshot_path}")

            # 关闭浏览器
            browser.close()
            logging.info("===== 测试完成 =====")

    except Exception as e:
        logging.error(f"测试失败: {str(e)}")
        # 发生错误时截图
        if 'page' in locals() and page:
            error_screenshot = f"error_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
            page.screenshot(path=error_screenshot)
            logging.info(f"错误截图已保存至: {error_screenshot}")
        raise


if __name__ == "__main__":
    main()